import { useState, useCallback } from 'react'
import {useLocation} from "umi";
import * as dd from 'dingtalk-jsapi'
import { login } from '@/services';

function parseCorpId(url, param) {
    var searchIndex = url.indexOf('?');
    var searchParams = url.slice(searchIndex + 1).split('&');
    for (var i = 0; i < searchParams.length; i++) {
        var items = searchParams[i].split('=');
        if (items[0].trim() == param) {
            return items[1].trim();
        }
    }
}

export default () => {
    const location = useLocation();
    const [user, setUser] = useState({})

    const originalUrl = location.href;
    let corpId = parseCorpId(originalUrl, 'corpId');

    const setUserData = useCallback(() => {
        // 获取钉钉authcode
        try {
            dd.ready(function () {
                // dd.ready参数为回调函数，在环境准备就绪时触发，jsapi的调用需要保证在该回调函数触发后调用，否则无效。
                try {
                    let requestAuthCode = dd.runtime.permission.requestAuthCode({
                        corpId: corpId
                    });
                    requestAuthCode.then((res) => {
                        console.log("----打印：", res); //----打印： 成功
                        alert(res)
                        login({})
                            .then(result => {
                                console.log(result)
                            })
                    });
                } catch (e) {
                    console.error(e);
                }

            });
        }catch (e) {
            console.error(e);
        }

        setUser({
            name: '',
            usercode: '',
            depts: [],
            jwt: ''
        })
    }, [])

    return { user, setUserData }
}